<template>
  <div class="trend-chart">
    <div class="changes">
      <Form>
        <Row :gutter="15">
          <Col :span="8">
            <form-field v-model="currentShare" label="股票" type="select" :datas="shares" />
          </Col>
          <Col :span="2">
            <Button type="primary" shape="circle" icon="ios-arrow-back" to="/tools/shares">返回</Button>
          </Col>
          <Col :span="14">
            <h3>自动刷新倒计时，剩余{{ countDown }}秒</h3>
          </Col>
        </Row>
      </Form>
    </div>
    <div id="canvas" style="width:100%;height:480px;"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
export default {
  data() {
    return {
      shares: [],
      autoHeight: 300,
      currentShare: '',
      chartTitle: '',
      echarts: null,
      echartsOption: [],
      countDown: 30,
      intervalHandlers: []
    };
  },
  methods: {
    RenderMetric() {
      let that = this;

      this.$http.get(`/api/shares/${this.currentShare}/statistics`).then(rs => {
        const d = rs.datas;

        that.echartsOption.series.length = 0;

        that.echartsOption.xAxis.data = d.map(function(m) {
          return `${m.Date} ${m.Time}`;
        });

        that.echartsOption.title.text = `走势图 - ${that.chartTitle}`;
        that.echartsOption.series.push({
          name: '当前价',
          type: 'line',
          yAxisIndex: 0,
          data: d.map(function(m) {
            return m.CurrentPrice.toFixed(2);
          }),
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: '平均值' }]
          }
        });

        that.echartsOption.series.push({
          name: '成交量',
          type: 'line',
          yAxisIndex: 1,
          data: d.map(function(m) {
            return (m.SaleCounts / 10000).toFixed(2);
          })
        });

        // 使用刚指定的配置项和数据显示图表。
        that.echarts.setOption(that.echartsOption);
      });
    },
    loadShares() {
      this.$http.get('/api/shares/list').then(res => {
        this.shares = (res.datas || []).map(d => {
          return { text: d.Name, value: d.Code };
        });

        this.chartTitle = (this.shares.find(s => s.value == this.currentShare) || {}).text;
      });
    },
    ResizeChartPanel(area) {
      document.getElementById('canvas').style.height = area.height - 70 + 'px';
    }
  },
  watch: {
    $route() {
      this.currentShare = this.$route.params.code;
    },
    currentShare(val) {
      let item = this.shares.find(d => d.value == val);

      if (item) {
        this.chartTitle = item.text;
      }

      this.RenderMetric();
    }
  },
  mounted() {
    this.$bus.on('windowResizeChanged', client => {
      this.ResizeChartPanel(client);

      if (this.echarts) {
        this.echarts.resize();
      }
    });

    this.currentShare = this.$route.params.code;

    this.loadShares();

    this.intervalHandlers.forEach(handler => clearInterval(handler));
    this.intervalHandlers.length = 0;

    const $this = this;
    let handler1 = setInterval(() => {
      $this.RenderMetric();
    }, 30 * 1000);

    let handler2 = setInterval(() => {
      $this.countDown--;

      if (!$this.countDown) {
        $this.countDown = 30;
      }
    }, 1000);

    this.intervalHandlers.push(handler1, handler2);

    this.$nextTick(() => {
      this.echarts = echarts.init(document.getElementById('canvas'));

      this.echartsOption = {
        title: {
          text: `走势图 - ${$this.chartTitle}`
        },
        grid: {
          left: '30px',
          right: '30px',
          bottom: '10px',
          top: '80px',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          }
        },
        legend: {
          data: ['当前价', '成交量']
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            formatter: '{value}'
          },
          axisPointer: {
            show: true,
            label: {
              show: true,
              formatter: '{value}'
            }
          },
          data: []
        },
        yAxis: [
          {
            type: 'value',
            name: '当前价(元)',
            min: 0,
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '成交量(万股)',
            position: 'right',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: []
      };

      // 使用刚指定的配置项和数据显示图表。
      this.echarts.setOption(this.echartsOption);

      this.RenderMetric();
    });
  },
  destroyed() {
    this.intervalHandlers.forEach(handler => clearInterval(handler));
    this.intervalHandlers.length = 0;
  }
};
</script>

<style lang="less" scoped>
body {
  .content-wrapper {
    > * {
      padding: 0;
      background: transparent;
    }
  }

  .trend-chart {
    > .changes {
      background: #fff;
      border-radius: 5px;
      padding: 10px 15px;
      margin-bottom: 10px;

      .ivu-row {
        align-items: center;
      }
    }

    > #canvas {
      background: #fff;
      border-radius: 5px;
      padding: 5px 10px;
    }
  }
}
</style>
